package com.leyou.cart.service;

import com.leyou.cart.entity.Cart;
import com.leyou.common.auth.pojo.UserHolder;
import com.leyou.common.constants.LyConstants;
import com.leyou.common.exception.pojo.ExceptionEnum;
import com.leyou.common.exception.pojo.LyException;
import com.leyou.common.utils.JsonUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.BoundHashOperations;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.stream.Collectors;

@Service
public class CartService {

    @Autowired
    private StringRedisTemplate redisTemplate;

    /**
     * 分析购物车数据结构
     * String，hash，list，set，zSet
     *  这里为了放别修改某个购物车数据，采用hash结构：<key, <hKey, hValue>>
     *  key ----  userId
     *  hKey ---  skuId
     *  hValue -  Cart对象
     */
    public void saveCart(Cart cart) {
        //先获取当前用户id
        Long userId = UserHolder.getUserId();
        //获取当前用户购物车数据在redis中的key
        String key = LyConstants.CART_PRE+userId;
        //获取当前用户在redis中存储的购物车对象的hash
        BoundHashOperations<String, String, String> cartHash = redisTemplate.boundHashOps(key);
        //获取要添加的购物车对象的hKey
        String hKey = cart.getSkuId().toString();
        //判断当前购物车中是否有要添加的购物车对象
        if(cartHash.hasKey(hKey)){
            //得到当前购物车中对应的对象
            String oldCartStr = cartHash.get(hKey);
            //转成json
            Cart oldCart = JsonUtils.toBean(oldCartStr, Cart.class);
            //如果当前购物车中包含要添加的购物车对象，将二者的数量合并
            cart.setNum(cart.getNum()+oldCart.getNum());
        }
        //保存购物车
        cartHash.put(hKey, JsonUtils.toString(cart));
    }

    public List<Cart> findCarts() {
        //先获取当前用户id
        Long userId = UserHolder.getUserId();
        //获取当前用户购物车数据在redis中的key
        String key = LyConstants.CART_PRE+userId;
        //判断当前用户是否有购物车数据
        if(!redisTemplate.hasKey(key)){
            throw new LyException(ExceptionEnum.CARTS_NOT_FOUND);
        }
        //通过key获取hash
        BoundHashOperations<String, String, String> hashCart = redisTemplate.boundHashOps(key);
        //判空
        if(hashCart==null || hashCart.size()==0){
            throw new LyException(ExceptionEnum.CARTS_NOT_FOUND);
        }
        //得到hValue
        List<Cart> carts = hashCart.values()
                .stream()
                .map(cart -> JsonUtils.toBean(cart, Cart.class))
                .collect(Collectors.toList());
        return carts;
    }

    public void saveCarts(List<Cart> carts) {
        carts.forEach(cart -> {
            saveCart(cart);
        });
    }
}
